package zmee.pmct.formplugin.pmas;

import kd.bos.ai.util.JsonUtil;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.util.HttpClientUtils;
import zmee.util.DBUtil;
import zmee.util.GetCwgxAccessTokenUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeforeDeletePurContractPlugin extends AbstractOperationServicePlugIn {
    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject pur_contract = dataEntities[0];


        if (pur_contract != null) {
            String billno = pur_contract.get("billno").toString();

            HashMap<String,Object> inputs = new HashMap<>();
            inputs.put("billno",billno);
            String accesstoken = GetCwgxAccessTokenUtil.getAccesstoken("18205188770");
            String cqUrl = DBUtil.getParamValue("CQUrl");
            String url = "/kapi/app/iscb/sf_purcontractisexist";
            url=cqUrl+url;
            HashMap<String, String> header = new HashMap<>();
            header.put("accesstoken",accesstoken);
            String result = null;
            try {
                result = HttpClientUtils.postAppJson(url, header, inputs);
            } catch (IOException exception) {
                exception.printStackTrace();
            }

//            List<Object> inputs = new ArrayList<>(1);
//            inputs.add(billno);
//            //查询eas是否存在该编码的采购合同
//            Map result = DispatchServiceHelper.invokeBizService("isc", "iscb",
//                    "IscFlowService", "execute", "purcontractisexist", inputs);
            Map returndata = (Map) JsonUtil.decodeFromString(result,HashMap.class);
            Map data = (Map) returndata.get("data");
            Map output = (Map) data.get("output");
            boolean isexist = (boolean) output.get("isexist");
            //存在则禁止删除
            if (isexist){
                e.setCancel(true);
                e.setCancelMessage("查询到eas存在对应采购合同，不能删除。");
            }
        }

        super.beforeExecuteOperationTransaction(e);
    }
}
